<template>
  <el-config-provider :locale="zhCn">
    <div class="switch-model">
      <!-- 筛选条件与统计信息同行 -->
      <div class="filter-section-with-stats">
        <div class="filter-form-wrapper">
          <filter-form v-model="filterForm" :form-items="formItems" @search="handleSearch" @reset="resetFilter" @update:modelValue="handleFilterChange" />
        </div>
        <div class="header-stats-inline">
          <div class="stat-item">
            <span class="stat-number">{{ total }}</span>
            <span class="stat-label">总模型数</span>
          </div>
          <div class="stat-item">
            <span class="stat-number">{{ activeModels }}</span>
            <span class="stat-label">已启用</span>
          </div>
        </div>
      </div>

      <!-- 模型卡片展示区域 -->
      <div class="models-grid" v-loading="loading">
        <div v-for="model in modelList" :key="model.id" class="model-card" :class="{ 'is-active': model.aiChat || model.aiFriendCircleLikes }">
          <!-- 卡片头部 -->
          <div class="card-header">
            <div class="manufacturer-badge" :class="getManufacturerClass(model.modeManufacturer)">
              {{ getManufacturerName(model.modeManufacturer) }}
            </div>
            <div class="model-status" :class="{ active: model.aiChat || model.aiFriendCircleLikes }">
              <div class="status-dot"></div>
              <span>{{ model.aiChat || model.aiFriendCircleLikes ? '已启用' : '未启用' }}</span>
            </div>
          </div>

          <!-- 模型信息 -->
          <div class="model-info">
            <h3 class="model-name">{{ model.modeName }}</h3>
            <div class="model-meta">
              <div class="meta-item">
                <span class="meta-label">算力价格</span>
                <span class="meta-value">¥{{ model.computingPowerPrice }}</span>
              </div>
              <div class="meta-item">
                <span class="meta-label">输入Token</span>
                <span class="meta-value">¥{{ model.tokenInputPrice }}</span>
              </div>
              <div class="meta-item">
                <span class="meta-label">输出Token</span>
                <span class="meta-value">¥{{ model.tokenOutputToken }}</span>
              </div>
            </div>
          </div>

          <!-- 功能开关 -->
          <div class="function-switches">
            <div class="switch-item">
              <div class="switch-info">
                <div class="switch-icon">
                  <svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                    <path
                      d="M21 15C21 15.5304 20.7893 16.0391 20.4142 16.4142C20.0391 16.7893 19.5304 17 19 17H7L3 21V5C3 4.46957 3.21071 3.96086 3.58579 3.58579C3.96086 3.21071 4.46957 3 5 3H19C19.5304 3 20.0391 3.21071 20.4142 3.58579C20.7893 3.96086 21 4.46957 21 5V15Z"
                      stroke="currentColor"
                      stroke-width="2"
                      stroke-linecap="round"
                      stroke-linejoin="round"
                    />
                  </svg>
                </div>
                <span>AI聊天</span>
              </div>
              <el-switch
                v-model="model.aiChat"
                @change="(val: boolean) => handleStatusChange(model, 'aiChat', val)"
                :active-color="'#10b981'"
                :inactive-color="'#e5e7eb'"
                size="large"
              />
            </div>
            <div class="switch-item">
              <div class="switch-info">
                <div class="switch-icon">
                  <svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                    <path d="M2 21h4V9H2v12z" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" />
                    <path
                      d="M22 10c0-1.1-.9-2-2-2h-6.31l.95-4.57.03-.32c0-.41-.17-.79-.44-1.06L13 2 6.59 8.41C6.22 8.78 6 9.3 6 9.83V19c0 1.1.9 2 2 2h9c.83 0 1.54-.5 1.84-1.22l3.02-7.05c.09-.23.14-.47.14-.73v-1z"
                      stroke="currentColor"
                      stroke-width="2"
                      stroke-linecap="round"
                      stroke-linejoin="round"
                    />
                  </svg>
                </div>
                <span>朋友圈点赞</span>
              </div>
              <el-switch
                v-model="model.aiFriendCircleLikes"
                @change="(val: boolean) => handleStatusChange(model, 'aiFriendCircleLikes', val)"
                :active-color="'#3b82f6'"
                :inactive-color="'#e5e7eb'"
                size="large"
              />
            </div>
          </div>

          <!-- 卡片装饰 -->
          <div class="card-decoration"></div>
        </div>
      </div>

      <!-- 空状态 -->
      <div v-if="!loading && modelList.length === 0" class="empty-state">
        <div class="empty-icon">
          <svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
            <path
              d="M9 12L11 14L15 10M21 12C21 16.9706 16.9706 21 12 21C7.02944 21 3 16.9706 3 12C3 7.02944 7.02944 3 12 3C16.9706 3 21 7.02944 21 12Z"
              stroke="currentColor"
              stroke-width="2"
              stroke-linecap="round"
              stroke-linejoin="round"
            />
          </svg>
        </div>
        <h3>暂无模型数据</h3>
        <p>当前筛选条件下没有找到匹配的模型</p>
      </div>

      <!-- 分页 -->
      <div class="pagination-wrapper" v-if="total > 0">
        <pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :total="total" @pagination="handlePagination" />
      </div>
    </div>
  </el-config-provider>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { getSwitchModelList, updateSwitchModel } from '@/api/privateModel/switchModel';
import type { SwitchModelParams, SwitchModelListData } from '@/api/privateModel/switchModel';
import zhCn from 'element-plus/es/locale/lang/zh-cn';
import { useUserStore } from '@/store/modules/user';
import FilterForm from '@/components/FilterForm/index.vue';
import Pagination from '@/components/Pagination/index.vue';
import type { FormItem } from '@/components/FilterForm/index.vue';

// 获取userStore
const userStore = useUserStore();

// 筛选表单
const filterForm = reactive<SwitchModelParams>({
  modeManufacturer: '',
  modeName: '',
  accountType: userStore.tenantId
});

// 表单项配置
const formItems = computed<FormItem[]>(() => [
  {
    label: '模型厂商',
    prop: 'modeManufacturer',
    type: 'select',
    placeholder: '请选择',
    options: [
      { label: '全部', value: '' },
      { label: 'DeepSeek', value: 'DeepSeek' }
    ]
  },
  {
    label: '模型名称',
    prop: 'modeName',
    type: 'input',
    placeholder: '请输入模型名称'
  }
]);

// 分页相关
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);

// 加载状态
const loading = ref(false);

// 模型列表数据
const modelList = ref<SwitchModelListData['records']>([]);

// 计算已启用的模型数量
const activeModels = computed(() => {
  return modelList.value.filter((model) => model.aiChat || model.aiFriendCircleLikes).length;
});

// 获取厂商样式类
const getManufacturerClass = (manufacturer: string) => {
  const classes = {
    openai: 'openai',
    baidu: 'baidu',
    xunfei: 'xunfei'
  };
  return classes[manufacturer as keyof typeof classes] || 'default';
};

// 获取厂商显示名称
const getManufacturerName = (manufacturer: string) => {
  const names = {
    openai: 'OpenAI',
    baidu: '百度',
    xunfei: '讯飞'
  };
  return names[manufacturer as keyof typeof names] || manufacturer;
};

// 查询方法
const handleSearch = async (formData?: Record<string, any>) => {
  loading.value = true;
  try {
    // 使用传入的表单数据或当前的表单数据
    const searchData = formData || filterForm;
    const params = {
      modeManufacturer: searchData.modeManufacturer || undefined,
      modeName: searchData.modeName || undefined,
      accountType: userStore.tenantId,
      current: currentPage.value,
      size: pageSize.value
    };

    // 移除所有 undefined 的参数
    Object.keys(params).forEach((key) => {
      if (params[key as keyof typeof params] === undefined) {
        delete params[key as keyof typeof params];
      }
    });

    const res = await getSwitchModelList(params);
    if (res.data) {
      const listData = res.data as unknown as SwitchModelListData;
      modelList.value = listData.records;
      total.value = listData.total;
    }
  } catch (error) {
    console.error('获取模型列表失败：', error);
    ElMessage.error('获取模型列表失败');
  } finally {
    loading.value = false;
  }
};

// 重置筛选
const resetFilter = () => {
  filterForm.modeManufacturer = '';
  filterForm.modeName = '';
  currentPage.value = 1;
  pageSize.value = 10;
  handleSearch();
};

// 分页方法
const handlePagination = ({ pageNum, pageSize: size }: { pageNum: number; pageSize: number }) => {
  currentPage.value = pageNum;
  pageSize.value = size;
  handleSearch();
};

// 处理状态变更
const handleStatusChange = async (row: SwitchModelListData['records'][0], type: 'aiChat' | 'aiFriendCircleLikes', newStatus: boolean) => {
  try {
    const typeText = type === 'aiChat' ? 'AI聊天' : '朋友圈点赞';
    await ElMessageBox.confirm(`确定要${newStatus ? '启用' : '禁用'}该模型的${typeText}功能吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });

    // 如果启用，先将其他模型的相同类型状态设为 false
    if (newStatus) {
      modelList.value.forEach((model) => {
        if (model.id !== row.id) {
          model[type] = false;
        }
      });
    }

    // 这里 row[type] 已经是最新的状态，无需再赋值
    await updateSwitchModel({
      id: row.id,
      accountType: userStore.tenantId,
      aiChat: row.aiChat ? '1' : '0',
      aiFriendCircleLikes: row.aiFriendCircleLikes ? '1' : '0'
    });

    ElMessage.success('设置成功');
    handleSearch();
  } catch (error) {
    // 如果取消，需要把 UI 状态恢复
    row[type] = !newStatus;
    if (error !== 'cancel') {
      ElMessage.error('设置失败');
    }
  }
};

// 处理筛选条件变化
const handleFilterChange = (val: any) => {
  filterForm.modeManufacturer = val.modeManufacturer || '';
  filterForm.modeName = val.modeName || '';
};

// 初始化
onMounted(() => {
  handleSearch();
});
</script>

<style lang="scss" scoped>
.switch-model {
  min-height: 100vh;
  // background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 0;

  .page-header {
    background: rgba(255, 255, 255, 0.95);
    backdrop-filter: blur(10px);
    padding: 40px 0 20px 0;
    margin-bottom: 30px;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);

    .header-stats-only {
      display: flex;
      justify-content: center;
      gap: 40px;
      max-width: 600px;
      margin: 0 auto;
    }
    .stat-item {
      text-align: center;
      .stat-number {
        display: block;
        font-size: 32px;
        font-weight: 700;
        color: #667eea;
      }
      .stat-label {
        font-size: 16px;
        color: #6b7280;
        margin-top: 4px;
      }
    }
  }

  .filter-section-with-stats {
    display: flex;
    justify-content: space-between;
    align-items: flex-end;
    max-width: 1200px;
    margin: 15px auto 0px;
    padding: 15px 20px;
    .filter-form-wrapper {
      width: 80%;
    }
    .header-stats-inline {
      display: flex;
      gap: 24px;
      margin-bottom: 15px;
      .stat-item {
        text-align: right;
        .stat-number {
          font-size: 22px;
          font-weight: 600;
          color: #667eea;
        }
        .stat-label {
          font-size: 15px;
          color: #6b7280;
          margin-left: 4px;
        }
      }
    }
  }

  .models-grid {
    max-width: 1200px;
    margin: 0 auto;
    padding: 0 20px;
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(380px, 1fr));
    gap: 24px;
    margin-bottom: 40px;

    .model-card {
      background: rgba(255, 255, 255, 0.95);
      backdrop-filter: blur(10px);
      border-radius: 20px;
      padding: 24px;
      position: relative;
      overflow: hidden;
      transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
      border: 1px solid rgba(255, 255, 255, 0.2);
      box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);

      &:hover {
        transform: translateY(-8px);
        box-shadow: 0 20px 40px rgba(0, 0, 0, 0.15);
      }

      &.is-active {
        border-color: #10b981;
        box-shadow: 0 8px 32px rgba(16, 185, 129, 0.2);

        .card-decoration {
          background: linear-gradient(135deg, #10b981, #059669);
        }
      }

      .card-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 20px;

        .manufacturer-badge {
          padding: 8px 16px;
          border-radius: 20px;
          font-size: 12px;
          font-weight: 600;
          text-transform: uppercase;
          letter-spacing: 0.5px;

          &.openai {
            background: linear-gradient(135deg, #10a37f, #0d8a6f);
            color: white;
          }

          &.baidu {
            background: linear-gradient(135deg, #2932e1, #1e40af);
            color: white;
          }

          &.xunfei {
            background: linear-gradient(135deg, #f59e0b, #d97706);
            color: white;
          }

          &.default {
            background: linear-gradient(135deg, #6b7280, #4b5563);
            color: white;
          }
        }

        .model-status {
          display: flex;
          align-items: center;
          gap: 8px;
          font-size: 14px;
          color: #6b7280;

          &.active {
            color: #10b981;
          }

          .status-dot {
            width: 8px;
            height: 8px;
            border-radius: 50%;
            background: currentColor;
          }
        }
      }

      .model-info {
        margin-bottom: 24px;

        .model-name {
          font-size: 20px;
          font-weight: 600;
          color: #1f2937;
          margin: 0 0 16px 0;
        }

        .model-meta {
          display: grid;
          grid-template-columns: repeat(3, 1fr);
          gap: 12px;

          .meta-item {
            text-align: center;
            padding: 12px;
            background: #f8fafc;
            border-radius: 12px;

            .meta-label {
              display: block;
              font-size: 12px;
              color: #6b7280;
              margin-bottom: 4px;
            }

            .meta-value {
              display: block;
              font-size: 16px;
              font-weight: 600;
              color: #1f2937;
            }
          }
        }
      }

      .function-switches {
        display: flex;
        flex-direction: column;
        gap: 16px;

        .switch-item {
          display: flex;
          justify-content: space-between;
          align-items: center;
          padding: 16px;
          background: #f8fafc;
          border-radius: 12px;
          transition: all 0.3s ease;

          &:hover {
            background: #f1f5f9;
          }

          .switch-info {
            display: flex;
            align-items: center;
            gap: 12px;

            .switch-icon {
              width: 24px;
              height: 24px;
              color: #6b7280;
            }

            span {
              font-size: 14px;
              font-weight: 500;
              color: #374151;
            }
          }
        }
      }

      .card-decoration {
        position: absolute;
        top: 0;
        right: 0;
        width: 60px;
        height: 60px;
        background: linear-gradient(135deg, #e5e7eb, #d1d5db);
        border-radius: 0 20px 0 60px;
        opacity: 0.1;
        transition: all 0.3s ease;
      }
    }
  }

  .empty-state {
    text-align: center;
    padding: 80px 20px;
    max-width: 400px;
    margin: 0 auto;

    .empty-icon {
      width: 80px;
      height: 80px;
      margin: 0 auto 24px;
      color: #9ca3af;
    }

    h3 {
      font-size: 20px;
      font-weight: 600;
      color: #374151;
      margin: 0 0 8px 0;
    }

    p {
      color: #6b7280;
      margin: 0;
    }
  }

  .pagination-wrapper {
    max-width: 1200px;
    margin: 0 auto;
    padding: 0 20px 40px;
    display: flex;
    justify-content: center;
  }
}

// 响应式设计
@media (max-width: 768px) {
  .switch-model {
    .models-grid {
      grid-template-columns: 1fr;
      gap: 16px;
    }
  }
}

// 自定义滚动条
::-webkit-scrollbar {
  width: 8px;
}

::-webkit-scrollbar-track {
  background: #f1f5f9;
}

::-webkit-scrollbar-thumb {
  background: linear-gradient(135deg, #667eea, #764ba2);
  border-radius: 4px;
}

::-webkit-scrollbar-thumb:hover {
  background: linear-gradient(135deg, #5a67d8, #6b46c1);
}
</style>